<?php
/**
 * WithdrawRepo.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-06-01 15:22:05
 * @modified   2023-06-01 15:22:05
 */

namespace Beike\Seller\Repositories;

use Beike\Seller\Models\Withdraw;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class WithdrawRepo
{
    /**
     * 创建一个记录
     * @param $data
     * @return Builder|Model
     */
    public static function create($data): Model|Builder
    {
        $data = [
            'seller_id'     => $data['seller_id'] ?? current_seller_user()->seller_id,
            'bank'          => $data['bank'],
            'bank_account'  => $data['bank_account'],
            'bank_name'     => $data['bank_name'],
            'currency_code' => $data['currency_code'],
            'amount'        => $data['amount'],
            'description'   => $data['description'],
            'status'        => $data['status'],
        ];

        return Withdraw::query()->create($data);
    }

    /**
     * @param $id
     * @param $data
     * @return Builder|Builder[]|Collection|Model
     * @throws \Exception
     */
    public static function update($id, $data): Model|Collection|Builder|array
    {
        $withdraw = Withdraw::query()->find($id);
        if (! $withdraw) {
            throw new \Exception("Withdraw id {$id} not exist");
        }
        $withdraw->update($data);

        return $withdraw;
    }

    /**
     * @param $id
     * @return Builder|Builder[]|Collection|Model|null
     */
    public static function find($id): Model|Collection|Builder|array|null
    {
        return Withdraw::query()->findOrFail($id);
    }

    /**
     * @param $id
     * @return void
     */
    public static function delete($id)
    {
        $withdraw = Withdraw::query()->find($id);
        if ($withdraw) {
            $withdraw->delete();
        }
    }

    /**
     * 获取列表
     *
     * @return Builder[]|Collection
     */
    public static function list($sellerId = 0): Collection|array
    {
        $builder = Withdraw::query()->orderBy('id', 'desc');

        if ($sellerId) {
            $builder->where('seller_id', $sellerId);
        } else {
            $builder->with('seller');
        }

        return $builder->get();
    }
}
